package com.scalar.forecast.salesForecastEntry.actionCommands;

import com.scalar.forecast.actionCommands.ActionCommand;
import com.scalar.forecast.salesForecastEntry.forms.SalesForecastEntryForm;
import com.scalar.forecast.salesForecastEntry.dao.SalesForecastEntryDAO;
import com.scalar.forecast.forecastReports.dao.ForecastReportsDAO;
import com.scalar.forecast.commons.SessionKeys;
import com.scalar.forecast.salesPersonSetup.dao.SalesPersonSetupDAO;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.ArrayList;

/**
 * User: Sujan
 * Date: Jul 13, 2005
 * Time: 4:48:25 PM
 */
public class SalesForecastEntrySearchCommand extends ActionCommand
{
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception
    {
        SalesForecastEntryForm forecastEntryForm =  ( SalesForecastEntryForm ) form;
        HttpSession session     = request.getSession();
        User pUser = (User)session.getAttribute ( SessionKeys.USER_KEY );
        Calendar now    = Calendar.getInstance();
        forecastEntryForm.setMonth( now.get ( Calendar.MONTH ) );
        forecastEntryForm.setYear( now.get( Calendar.YEAR ) );
        forecastEntryForm.setShowNext( 12 );//default 12 months
        request.setAttribute( "monthsList", SalesForecastEntryDAO.getMonthsList() );
        request.setAttribute( "yearsList", SalesForecastEntryDAO.getYearList() );
        int spersonId   = -1;
        ArrayList salesPersons;
        try
        {
            spersonId  = Integer.parseInt ( (String)session.getAttribute ( SessionKeys.USER_SALESPERSON_ID ) );
        }
        catch ( NumberFormatException e )
        {
              spersonId = -1;
        }
        if ( pUser.isActionAllowed( Functionality.FORECAST_ENTRY_FOR_ALL_SALES_PERSONS, User.USER_ACTION_MODIFY ) ) //SUPER USER
        {
            salesPersons = SalesPersonSetupDAO.getSalesPersonList();
        }
        else
        {
            salesPersons = ForecastReportsDAO.getSalesPersonsWithManagerList(spersonId);
        }
        if ( salesPersons != null && salesPersons.size() > 1 )
        {
            salesPersons.add ( 0, new LabelValueBean ( "--All Sales Persons--", "0" ) );
        }
        request.setAttribute ( "sPersonList", salesPersons );
        forecastEntryForm.setSpersonId( spersonId );
        return mapping.findForward( "salesForecastEntrySearch" );
    }

}
